/**
 *	Amantes Test
 *	@author Ncomunicaciones
 */

// randomize
(function($) {

$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);

      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.remove(childElem);  

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      

  });    
}
})(jQuery);

window.test = (function() {

// vars
var scrollable, timer,
	done = 0,
	total = 0,
	currentDone = 0,
	currentTotal = 0,
	love_attitudes = {};
	
/**
 *	Init
 */
function init() {
	// window
	$(window).on({
	resize: function() {
		if(scrollable) scrollable.seekTo(scrollable.getIndex(), 0);
	}});
	// randomize
	$("div.items").randomize("fieldset");
	$("fieldset.first").prependTo("div.items");
	$("fieldset.last").appendTo("div.items");
	// scrollable
	scrollable = $("form").scrollable({keyboard: false}).data("scrollable");
	// skin
	$("input:radio").each(function(index, element) {
		var $this = $(this);
		$this.wrap('<span class="radio" />').css({"opacity": 0, "position": "absolute"}).parent().append($this.val());
	});
	// btn
	$("a.form-prev").on("click", prev);
	$("a.form-next").on("click", next);
	$("input:button").on("click", next);
	// keyboard
	$(document).on("keydown", function(e) {
		switch(e.which) {
		case 13:
		case 37:
		case 39:
			e.preventDefault();	
		}
	});
	$(document).on("keyup", function(e) {
		var target = currentItem().find(".question");
		if(e.which === 37) prev();
		if(e.which === 13 || e.which === 39) next();
		if(currentItem().find(".question").length > 1) target = target.not(".done").eq(0);
		target.find("label").filter(function() {
			return ($(this).find("input").val() === String.fromCharCode(e.which) || $(this).find("input").val() === String.fromCharCode(e.which - 48));
		}).find("input").trigger("click").trigger("change");
	});
	// input
	$("input:radio").on("change", function() {
		var $this = $(this);
		$this.closest("label").siblings().removeClass("checked");
		$this.closest("div.question").find("label").removeClass("checked");
		$this.closest("label").addClass("checked").closest("div.question").addClass("done");
		update();
		if(currentItem().prevAll().andSelf().find("div.question").length === currentItem().prevAll().andSelf().find(".done").length && $(this).closest("div.question").length) startCountdown();
	});
	$("#main-form").on("click", "label", function(e) {
		if($(this).hasClass("disabled")) e.preventDefault();
	});
	// update
	update();
	
	function update() {
		var percent;
		total = $("div.question").length;
		done = $("div.done").length,
		percent = done / total * 100;
		$("#progress-text").text(done + " de " + total + " preguntas respondidas");
		$("#progress-bar").children().css({"width": percent + "%"});
		love_attitudes = {eros: 0, ludus: 0, storge: 0, pragma: 0, mania: 0, agape: 0};
		$("div.question").each(function() {
			var attitude = $(this).data("attitude"),
				value = parseInt($(this).find("input:checked").val());
			love_attitudes[attitude] += $.isNumeric(value) ? value : 0;
		});
		$.each(love_attitudes, function(k, v) {
			var width = (v / 16) * 360;
			$("div.chart").find("." + k).css({"width": width}).find(".qty").text(v);
		});
	}
	
	function currentItem() {
		return scrollable.getItems().eq(scrollable.getIndex());
	}
	
	function startCountdown() {
		clearTimeout(timer);
		$("#timer").css("visibility", "visible");
		timer = setTimeout(next, 700);
	}
	
	function validateUserData() {
		var isValid = true,
			$form = $("form.test"),
			$inputs = $form.find("fieldset").eq(0).find("input"),
			edad = $.trim($inputs.filter("[name=edad]").val());
			
		if(!edad || !$.isNumeric(edad) || edad < 12 || edad > 100) {
			$inputs.filter("[name=edad]").css("border-color", "red");
			isValid = false;
		}
		else { $inputs.filter("[name=edad]").css("border-color", ""); }
		
		if(!$inputs.filter("[name=sexo]:checked").length) {
			$inputs.filter("[name=sexo]").parent().css("border-color", "red");
			isValid = false;
		}
		else { $inputs.filter("[name=sexo]").parent().css("border-color", ""); }
		if(!isValid) alert("Por favor llene todos los campos y  asegúrese de que están en el formato correcto antes de continuar");
		return isValid;
	}
	
	function updateUI(direction) {		
		var currentPosition = scrollable.getIndex() + direction;
		if(currentPosition < 2) {
			$("a.form-prev").hide();
			if(currentPosition < 1)
				$("p.lead").show();
			else
				$("p.lead").hide();
		}
		else {
			$("a.form-prev").show();
			$("p.lead").hide();
		}
		if(currentPosition === $("fieldset").length - 1) {
			$("a.form-next").add("a.form-prev").hide();
			$("img.form-more").show();
			submitData();
		}
	}
	
	function submitData() {
		$.post("test_handler.php", $("form.test").serialize());
	}
	
	function prev() {
		updateUI(-1);
		clearTimeout(timer);
		scrollable.prev();
		$("#timer").removeAttr("style");
	}
	
	function next() {
		currentTotal = currentItem().prevAll().andSelf().find(".question").length,
		currentDone = currentItem().prevAll().andSelf().find(".done").length;
		if(currentDone === currentTotal && validateUserData()) {
			updateUI(1);
			clearTimeout(timer);
			scrollable.next();
			$("#timer").removeAttr("style");
		}
	}
}

return {
	init: init	
}})();

window.test.init();